#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <fstream>
#include <sstream>
#include <regex>
#include <sys/stat.h>
#include "../server.hpp"

std::unordered_map<int, std::string> _status_msg = {
    {100,  "Continue"},
    {101,  "Switching Protocol"},
    {102,  "Processing"},
    {103,  "Early Hints"},
    {200,  "OK"},
    {201,  "Created"},
    {202,  "Accepted"},
    {203,  "Non-Authoritative Information"},
    {204,  "No Content"},
    {205,  "Reset Content"},
    {206,  "Partial Content"},
    {207,  "Multi-Status"},
    {208,  "Already Reported"},
    {226,  "IM Used"},
    {300,  "Multiple Choice"},
    {301,  "Moved Permanently"},
    {302,  "Found"},
    {303,  "See Other"},
    {304,  "Not Modified"},
    {305,  "Use Proxy"},
    {306,  "unused"},
    {307,  "Temporary Redirect"},
    {308,  "Permanent Redirect"},
    {400,  "Bad Request"},
    {401,  "Unauthorized"},
    {402,  "Payment Required"},
    {403,  "Forbidden"},
    {404,  "Not Found"},
    {405,  "Method Not Allowed"},
    {406,  "Not Acceptable"},
    {407,  "Proxy Authentication Required"},
    {408,  "Request Timeout"},
    {409,  "Conflict"},
    {410,  "Gone"},
    {411,  "Length Required"},
    {412,  "Precondition Failed"},
    {413,  "Payload Too Large"},
    {414,  "URI Too Long"},
    {415,  "Unsupported Media Type"},
    {416,  "Range Not Satisfiable"},
    {417,  "Expectation Failed"},
    {418,  "I'm a teapot"},
    {421,  "Misdirected Request"},
    {422,  "Unprocessable Entity"},
    {423,  "Locked"},
    {424,  "Failed Dependency"},
    {425,  "Too Early"},
    {426,  "Upgrade Required"},
    {428,  "Precondition Required"},
    {429,  "Too Many Requests"},
    {431,  "Request Header Fields Too Large"},
    {451,  "Unavailable For Legal Reasons"},
    {501,  "Not Implemented"},
    {502,  "Bad Gateway"},
    {503,  "Service Unavailable"},
    {504,  "Gateway Timeout"},
    {505,  "HTTP Version Not Supported"},
    {506,  "Variant Also Negotiates"},
    {507,  "Insufficient Storage"},
    {508,  "Loop Detected"},
    {510,  "Not Extended"},
    {511,  "Network Authentication Required"}   
};

std::unordered_map<std::string, std::string> _mime_msg = {
    {".aac",        "audio/aac"},
    {".abw",        "application/x-abiword"},
    {".arc",        "application/x-freearc"},
    {".avi",        "video/x-msvideo"},
    {".azw",        "application/vnd.amazon.ebook"},
    {".bin",        "application/octet-stream"},
    {".bmp",        "image/bmp"},
    {".bz",         "application/x-bzip"},
    {".bz2",        "application/x-bzip2"},
    {".csh",        "application/x-csh"},
    {".css",        "text/css"},
    {".csv",        "text/csv"},
    {".doc",        "application/msword"},
    {".docx",       "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot",        "application/vnd.ms-fontobject"},
    {".epub",       "application/epub+zip"},
    {".gif",        "image/gif"},
    {".htm",        "text/html"},
    {".html",       "text/html"},
    {".ico",        "image/vnd.microsoft.icon"},
    {".ics",        "text/calendar"},
    {".jar",        "application/java-archive"},
    {".jpeg",       "image/jpeg"},
    {".jpg",        "image/jpeg"},
    {".js",         "text/javascript"},
    {".json",       "application/json"},
    {".jsonld",     "application/ld+json"},
    {".mid",        "audio/midi"},
    {".midi",       "audio/x-midi"},
    {".mjs",        "text/javascript"},
    {".mp3",        "audio/mpeg"},
    {".mpeg",       "video/mpeg"},
    {".mpkg",       "application/vnd.apple.installer+xml"},
    {".odp",        "application/vnd.oasis.opendocument.presentation"},
    {".ods",        "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt",        "application/vnd.oasis.opendocument.text"},
    {".oga",        "audio/ogg"},
    {".ogv",        "video/ogg"},
    {".ogx",        "application/ogg"},
    {".otf",        "font/otf"},
    {".png",        "image/png"},
    {".pdf",        "application/pdf"},
    {".ppt",        "application/vnd.ms-powerpoint"},
    {".pptx",       "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar",        "application/x-rar-compressed"},
    {".rtf",        "application/rtf"},
    {".sh",         "application/x-sh"},
    {".svg",        "image/svg+xml"},
    {".swf",        "application/x-shockwave-flash"},
    {".tar",        "application/x-tar"},
    {".tif",        "image/tiff"},
    {".tiff",       "image/tiff"},
    {".ttf",        "font/ttf"},
    {".txt",        "text/plain"},
    {".vsd",        "application/vnd.visio"},
    {".wav",        "audio/wav"},
    {".weba",       "audio/webm"},
    {".webm",       "video/webm"},
    {".webp",       "image/webp"},
    {".woff",       "font/woff"},
    {".woff2",      "font/woff2"},
    {".xhtml",      "application/xhtml+xml"},
    {".xls",        "application/vnd.ms-excel"},
    {".xlsx",       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml",        "application/xml"},
    {".xul",        "application/vnd.mozilla.xul+xml"},
    {".zip",        "application/zip"},
    {".3gp",        "video/3gpp"},
    {".3g2",        "video/3gpp2"},
    {".7z",         "application/x-7z-compressed"}
};

class Util
{
public:
    // 将src字符串通过sep进行分割，然后插入到arry中
    static size_t Split(const std::string& src, const std::string& sep, std::vector<std::string>* arry)
    {
        size_t offset = 0;
        while (offset < src.size())
        {
            size_t pos = src.find(sep, offset);
            if (pos == std::string::npos)
            {
                arry->push_back(src.substr(offset));
                return arry->size();
            }
            if (pos != offset)
                arry->push_back(src.substr(offset, pos - offset));
            offset = pos + sep.size();
        }
        return arry->size();
    }
    
    static bool ReadFile(const std::string& filename, std::string* buf)
    {
        std::ifstream ifs(filename, std::ios::binary);
        if (!ifs.is_open())
        {
            ERR_LOG("OPEN %s FILE FAILED!", filename.c_str());
            return false;
        }
        ifs.seekg(0, ifs.end);
        size_t fsize = ifs.tellg();
        ifs.seekg(0, ifs.beg);
        buf->resize(fsize);
        ifs.read(&(*buf)[0], fsize);
        if (!ifs.good())
        {
            ERR_LOG("READ %s FILE FAILED!", filename.c_str());
            ifs.close();
            return false;
        }
        ifs.close();
        return true;
    }

    static bool WriteFile(const std::string& filename, const std::string& buf)
    {
        std::ofstream ofs(filename, std::ios::binary | std::ios::trunc);
        if (!ofs.is_open())
        {
            ERR_LOG("OPEN %s FILE FAILED!", filename.c_str());
            return false;
        }
        ofs.write(buf.c_str(), buf.size());
        if (!ofs.good())
        {
            ERR_LOG("WRITE %s FILE FAILED!", filename.c_str());
            ofs.close();
            return false;
        }
        ofs.close();
        return true;
    }

    // URL编码：避免URL中资源路径与查询字符串中的特殊字符与HTTP请求中特殊字符产生歧义
    // 编码格式：将特殊字符的ASCII码值转换成两个十六进制的字符,前缀%. 如：C++ -> C%2B%2B
    // 不编码的特殊字符：RFC3986文档规定 . - _ ~以及字母、数字属于绝对不编码字符
    // RFC3986文档规定:编码格式为%HH，W3C标准规定，查询字符串中的空格需要编码为+，解码则是+转空格
    static std::string UrlEncode(const std::string& url, bool convert_space_to_plus)
    {
        std::string res;
        for(auto& c : url)
        {
            if (c == '.' || c == '-' || c == '_' || c == '~' || isalnum(c))
            {
                res += c;
                continue;
            }
            if (c == ' ' && convert_space_to_plus)
            {
                res += '+';
                continue;
            }
            char tmp[4] = {0};
            snprintf(tmp, 4, "%%%02X", c);
            res += tmp;
        }
        return res;
    }

    static char HEXTOI(char c)
    {
        if (c >= '0' && c <= '9')
            return c - '0';
        else if (c >= 'a' && c <= 'z')
            return c - 'a' + 10;
        else if (c >= 'A' && c <= 'Z')
            return c - 'A' + 10;
        return -1;
    }
    // URL解码：遇到了%，则将其紧随其后的两个字符转换为数字，第一个数字左移四位，然后加上第二个数字
    // 比如+也就是2b，转换成数字：2与11  2 << 4 + 11 = 32+11=43
    static std::string UrlDecode(const std::string& url, bool convert_plus_to_space)
    {
        std::string res;
        for (int i = 0; i < url.size(); i++)
        {
            if (url[i] == '+' && convert_plus_to_space)
            {
                res += ' ';
                continue;
            }
            if (url[i] == '%' && (i+2) < url.size())
            {
                char v1 = HEXTOI(url[i+1]);
                char v2 = HEXTOI(url[i+2]);
                char v = v1 * 16 + v2;
                res += v;
                i += 2;
                continue;
            }
            res += url[i];
        }
        return res;
    }

    static std::string StatusDesc(int status)
    {
        auto it = _status_msg.find(status);
        if (it == _status_msg.end())
        {
            return "Unknown";
        }
        return it->second;
    }

    // 根据文件后缀获取mime
    static std::string ExtMime(const std::string& filename)
    {
        size_t pos = filename.find_last_of(".");
        if (pos == std::string::npos)
            return "application/octet-stream";
        std::string ext = filename.substr(pos);
        auto it = _mime_msg.find(ext);
        if (it == _mime_msg.end())
            return "application/octet-stream";
        return it->second;
    }

    // 判断一个文件是否是目录
    static bool IsDirectory(const std::string& filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
            return false;
        return S_ISDIR(st.st_mode);
    }

    static bool IsRegular(const std::string& filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
            return false;
        return S_ISREG(st.st_mode);
    }

    // 判断http请求资源路径的有效性
    // 一般是从web根目录开始的，如果跑到根目录之外比如：/../index.html则有问题
    // 思想：切分路径，计算目录深度，若有一步跑到根目录之外，直接认定为非法路径
    static bool ValidPath(const std::string& path)
    {
        std::vector<std::string> subdir;
        Split(path, "/", &subdir);
        int level = 0;
        for (auto& e: subdir)
        {
            if (e == "..")
            {
                level--;
                if (level < 0) return false;
                continue;
            }
            level++;
        }
        return true;
    }
};


class HttpRequest
{
public:
    std::string _method;                                        // 请求方法
    std::string _path;                                          // 资源路径
    std::string _version;                                       // HTTP版本
    std::string _body;                                          // 请求正文
    std::smatch _matches;                                       // 资源路径的正则提取数据
    std::unordered_map<std::string, std::string> _headers;      // 请求头
    std::unordered_map<std::string, std::string> _params;       // 查询字符串
public:
    HttpRequest():_version("HTTP/1.1"){}
    void Reset()
    {
        _method.clear();
        _path.clear();
        _version = "HTTP/1.1";
        _body.clear();
        std::smatch match;
        _matches.swap(match);
        _headers.clear();
        _params.clear(); 
    }
    void SetHeader(const std::string& key, const std::string& val)
    {
        _headers.insert(std::make_pair(key, val));
    }
    bool HasHeader(const std::string& key) const
    {
        auto it = _headers.find(key);
        return it != _headers.end();
    }
    std::string GetHeader(const std::string& key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
            return "";
        return it->second;
    } 
    void SetParam(const std::string& key, const std::string& val)
    {
        _params.insert(std::make_pair(key, val));
    }
    bool HasParam(const std::string& key)
    {
        auto it = _params.find(key);
        return it != _params.end();
    }
    std::string GetParam(const std::string& key)
    {
        auto it = _params.find(key);
        if (it == _params.end())
            return "";
        return it->second;
    } 
    size_t ContentLength()
    {
        auto it = _headers.find("Content-Length");
        if (it == _headers.end())
            return 0;
        std::string res = it->second;
        return std::stol(res);
    }
    // 判断是否是短连接
    bool Close() const
    {
        if (HasHeader("Connection") && GetHeader("Connection") == "keep-alive")
            return false;
        return true;
    }
};

class HttpResponse
{
public:
    int _status;                                            // 状态码
    bool _redirect_flag;                                    // 重定向标志
    std::string _body;                                      // 响应正文
    std::string _redirect_url;                              // 重定向url
    std::unordered_map<std::string, std::string> _headers;  // 响应头部
public:
    HttpResponse():_status(200), _redirect_flag(false){}
    HttpResponse(int status):_status(status), _redirect_flag(false){}
    void Reset()
    {
        _status = 200;
        _redirect_flag = false;
        _body.clear();
        _redirect_url.clear();
        _headers.clear();
    }
    void SetHeader(const std::string& key, const std::string& val)
    {
        _headers.insert(std::make_pair(key, val));
    }
    bool HasHeader(const std::string& key)
    {
        auto it = _headers.find(key);
        return it != _headers.end();
    }
    std::string GetHeader(const std::string& key)
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
            return "";
        return it->second;
    }  
    void SetContent(const std::string& content, const std::string& type = "text/html")
    {
        _body = content;
        SetHeader("Content-Type", type);
    }
    void SetRedirect(const std::string& url, int status = 302)
    {
        _status = status;
        _redirect_flag = true;
        _redirect_url = url;
    }
    // 判断是否是短连接
    bool Close()
    {
        if (HasHeader("Connection") && GetHeader("Connection") == "keep-alive")
            return false;
        return true;
    }
};

#define MAX_LINE 8192
typedef enum {
    RECV_HTTP_ERROR,
    RECV_HTTP_LINE,
    RECV_HTTP_HEAD,
    RECV_HTTP_BODY,
    RECV_HTTP_OVER,
}HttpRecvStatus;
class HttpContext
{
private:
    int _resp_status;               // 响应状态码
    HttpRecvStatus _recv_status;    // 已经接收和解析的阶段状态
    HttpRequest _request;           // 已经解析得到的信息
private:
    bool ParseHttpLine(const std::string& line)
    {   
        std::smatch matches;
        std::regex e("(GET|HEAD|PUT|DELETE|POST) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01])(?:\n|\r\n)?", std::regex::icase); 
        bool ret = std::regex_match(line, matches, e);
        if (ret == false)
        {
            _recv_status = RECV_HTTP_ERROR;
            _resp_status = 400;//BAD REQUEST
            return false;
        }

        // 0: GET /zzy/login?username=zhangsan&password=123456 HTTP/1.1\r\n
        // 1: GET
        // 2: /zzy/login
        // 3: username=zhangsan&password=123456
        // 4: HTTP/1.1
        _request._method = matches[1];
        std::transform(_request._method.begin(), _request._method.end(), _request._method.begin(), ::toupper);
        _request._path = Util::UrlDecode(matches[2], false);
        _request._version = matches[4];
        std::vector<std::string> array;
        Util::Split(matches[3], "&", &array);
        for (auto& e : array)
        {
            size_t pos = e.find("=");
            if (pos == std::string::npos)
            {
                _recv_status = RECV_HTTP_ERROR;
                _resp_status = 400; // Bad Request
                return false;
            }
            std::string key = Util::UrlDecode(e.substr(0, pos), true);
            std::string val = Util::UrlDecode(e.substr(pos + 1), true);
            _request.SetParam(key, val);
        }
        return true;
    }

    bool RecvHttpLine(Buffer* buf)
    {
        if (_recv_status != RECV_HTTP_LINE) return false;
        std::string line = buf->GetLineAndPop();
        // 缓冲区的数据很长却还没有遇到\r\n,或者请求行太长，说明请求有问题.
        if (line.size() == 0)
        {
            if (buf->ReadableSize() > MAX_LINE)
            {
                _recv_status = RECV_HTTP_ERROR;
                _resp_status = 414;  // URI Too Long
                return false;
            }
            return true;
        }
        if (line.size() > MAX_LINE)
        {
            _recv_status = RECV_HTTP_ERROR;
            _resp_status = 414;  // URI Too Long
            return false;
        }
        bool ret = ParseHttpLine(line);
        if (ret == false)
        {
            return false;
        }
        // 进入头部处理阶段
        _recv_status = RECV_HTTP_HEAD;
        return true;
    }

    bool ParseHttpHead(std::string& line)
    {
        if (line.back() == '\n') line.pop_back();//末尾是换行则去掉换行字符
        if (line.back() == '\r') line.pop_back();//末尾是回车则去掉回车字符
        size_t pos = line.find(": ");
        if (pos == std::string::npos)
        {
            _recv_status = RECV_HTTP_ERROR;
            _resp_status = 400;
            return false;
        }
        std::string key = line.substr(0, pos);
        std::string val = line.substr(pos + 2);
        _request.SetHeader(key, val);
        return true;
    }

    bool RecvHttpHead(Buffer* buf)
    {
        if (_recv_status != RECV_HTTP_HEAD) return false;
        while (1)
        {
            std::string line = buf->GetLineAndPop();
            if (line.size() == 0)
            {
                if (buf->ReadableSize() > MAX_LINE)
                {
                    _recv_status = RECV_HTTP_ERROR;
                    _resp_status = 414;  // URI Too Long
                    return false;
                }
                return true;
            }
            if (line.size() > MAX_LINE)
            {
                _recv_status = RECV_HTTP_ERROR;
                _resp_status = 414;  // URI Too Long
                return false;
            }
            // 处理到空行退出
            if (line == "\n" || line == "\r\n")
                break;
            bool ret = ParseHttpHead(line);
            if (ret == false)
                return false;
        }
        _recv_status = RECV_HTTP_BODY;
        return true;
    }

    bool RecvHttpBody(Buffer* buf)
    {
        if (_recv_status != RECV_HTTP_BODY) return false;
        size_t content_length = _request.ContentLength();
        // 没有请求正文，处理结束
        if (content_length == 0)
        {
            _recv_status = RECV_HTTP_OVER;
            return true;
        }
        // 计算出还差多少正文长度
        size_t real_length = content_length - _request._body.size();
        // 如果剩余空间满足，直接取出处理结束。否则有多少取多少，下次再取。
        if (buf->ReadableSize() >= real_length)
        {
            _request._body.append(buf->ReadPosition(), real_length);
            buf->MoveReadOffset(real_length);
            _recv_status = RECV_HTTP_OVER;
            return true;
        }
        _request._body.append(buf->ReadPosition(), buf->ReadableSize());
        buf->MoveReadOffset(buf->ReadableSize());
        return true;
    }
public:
    HttpContext():_resp_status(200), _recv_status(RECV_HTTP_LINE) {}
    void Reset()
    {
        _resp_status = 200;
        _recv_status = RECV_HTTP_LINE;
        _request.Reset();
    }
    int RespStatus() { return _resp_status; }
    HttpRecvStatus RecvStatus() { return _recv_status; }
    HttpRequest& Request() { return _request; }
    // 接收并解析HTTP请求
    void RecvHttpRequest(Buffer* buf) 
    {
        // 这里处理完之后不应该break，而是继续向下处理，而不是退出等待新数据
        switch(_recv_status)
        {
            case RECV_HTTP_LINE: RecvHttpLine(buf);
            case RECV_HTTP_HEAD: RecvHttpHead(buf);
            case RECV_HTTP_BODY: RecvHttpBody(buf);
        }
    }
};

#define DEFAULT_TIMEOUT 10
class HttpServer
{
private:
    using Handler = std::function<void(const HttpRequest&, HttpResponse*)>;
    // 存储路径->处理方法的映射，但是考虑到/number/xxx 所以应该存储正则表达式/number/(\d+), 也就是一个std::string
    // 并且由于每次路由时都要将first取出来进行正则表达式的编译，为了提高效率，所以直接存储std::regex
    using Handlers = std::vector<std::pair<std::regex, Handler>>;
    Handlers _get_route;
    Handlers _post_route;
    Handlers _put_route;
    Handlers _delete_route;
    std::string _basedir;   // 静态资源路径
    TcpServer _server;
private:
    void ErrorHandler(const HttpRequest &req, HttpResponse *resp) {
        //1. 组织一个错误展示页面
        std::string body;
        body += "<html>";
        body += "<head>";
        body += "<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>";
        body += "</head>";
        body += "<body>";
        body += "<h1>";
        body += std::to_string(resp->_status);
        body += " ";
        body += Util::StatusDesc(resp->_status);
        body += "</h1>";
        body += "</body>";
        body += "</html>";
        //2. 将页面数据，当作响应正文，放入rsp中
        resp->SetContent(body, "text/html");
    }
    // 将HttpResponse要素组织成HTTP响应格式
    void WriteResponse(const PtrConnection& conn, const HttpRequest& req, HttpResponse& resp)
    {
        // 设置对应头部
        if (req.Close())
            resp.SetHeader("Connection", "close");
        else
            resp.SetHeader("Connection", "keep-alive");
        if (!resp._body.empty() && !resp.HasHeader("Content-Length"))
            resp.SetHeader("Content-Length", std::to_string(resp._body.size()));
        if (!resp._body.empty() && !resp.HasHeader("Content-Type"))
            resp.SetHeader("Content-Type", "application/octet-stream");
        if (resp._redirect_flag)
            resp.SetHeader("Location", resp._redirect_url);
        std::stringstream ss;
        ss << req._version << " " << std::to_string(resp._status) << " " << Util::StatusDesc(resp._status) << "\r\n";
        for (auto& e : resp._headers)
        {
            ss << e.first << ": " << e.second << "\r\n";
        }
        ss << "\r\n";
        ss << resp._body;
        conn->Send(ss.str().c_str(), ss.str().size());
    }
    bool iSFileHandler(const HttpRequest& req)
    {
        // 1.必须设置了静态资源根目录
        if (_basedir.empty()) return false;
        // 2.请求方法必须为GET / HEAD
        if (req._method != "GET" && req._method != "HEAD") return false;
        // 3.资源路径必须合法有效
        if (!Util::ValidPath(req._path)) return false;
        // 4.资源必须存在，且是普通文件
        // 请求的资源可能是一个单纯的目录，需要加上index.html后缀
        std::string req_path = _basedir + req._path;
        if (req_path.back() == '/')
        {
            req_path += "index.html";
        }
        if (!Util::IsRegular(req_path)) return false;
        return true;
    }
    // 静态资源的请求处理 将文件数据读取放到resp的body中，并设置mime
    void FileHandler(const HttpRequest& req, HttpResponse* resp)
    {
        std::string req_path = _basedir + req._path;
        if (req._path.back() == '/')  {
            req_path += "index.html";
        }
        bool ret = Util::ReadFile(req_path, &resp->_body);
        if (ret == false)
            return;
        std::string mime = Util::ExtMime(req_path);
        resp->SetHeader("Content-Type", mime);
        return;
    }
    // 功能性请求的分类处理
    void Dispatcher(HttpRequest& req, HttpResponse* resp, Handlers& handlers)
    {
        for (auto& handler : handlers)
        {
            const std::regex& re = handler.first;
            const Handler& functor = handler.second;
            bool ret = std::regex_match(req._path, req._matches, re);
            if (ret == false)
                continue;
            return functor(req, resp);
        }
        resp->_status = 404;
    }
    void Route(HttpRequest& req, HttpResponse* resp)
    {
        // 如果是静态资源请求获取返回，否则就找路由函数
        if (iSFileHandler(req))
        {
            return FileHandler(req, resp);
        }
        if (req._method == "GET" || req._method == "HEAD")
            return Dispatcher(req, resp, _get_route);
        if (req._method == "POST")
            return Dispatcher(req, resp, _post_route);
        if (req._method == "PUT")
            return Dispatcher(req, resp, _put_route);
        if (req._method == "DELETE")
            return Dispatcher(req, resp, _delete_route);
        // 都找不到说明服务端不支持这种请求方法
        resp->_status = 405; // Method Not Allowed
    }
    // 设置上下文
    void OnConnected(const PtrConnection& conn) 
    {
        conn->SetContext(HttpContext());
        DBG_LOG("NEW CONNECTION %p", conn.get());
    }
    // 数据解析+处理
    void OnMessage(const PtrConnection& conn, Buffer* buf)
    {
        while (buf->ReadableSize() > 0)
        {
            // 1.获取上下文 
            HttpContext* context = conn->GetContext()->get<HttpContext>();
            // 2.进行数据的读取解析
            context->RecvHttpRequest(buf);
            HttpRequest& req = context->Request();
            HttpResponse resp(context->RespStatus());
            // 2.1解析出错，直接回复出错的响应并关闭连接
            if (context->RespStatus() >= 400)
            {
                ErrorHandler(req, &resp);
                WriteResponse(conn, req, resp);
                context->Reset();  // 防止出错陷入死循环
                buf->MoveReadOffset(buf->ReadableSize());//出错了就把缓冲区数据清空
                conn->ShutDown();
                return;
            }
            // 2.2没有处理完数据，那就直接返回等待下次数据到来
            if (context->RecvStatus() != RECV_HTTP_OVER)
            {
                return;
            }
            // 3.进行路由+业务处理
            Route(req, &resp);
            // 4.对HttpResponse进行组织发送
            WriteResponse(conn, req, resp);
            // 5.重置上下文进行下次处理
            context->Reset();
            // 6.判断长短连接看是否关闭或者继续处理
            if (resp.Close()) conn->ShutDown();
        }
    }
public:
    HttpServer(uint16_t port, int timeout = DEFAULT_TIMEOUT):_server(port)
    {
        _server.EnableInactiveRelease(timeout);
        _server.SetConnectedCallBack(std::bind(&HttpServer::OnConnected, this, std::placeholders::_1));
        _server.SetMessageCallBack(std::bind(&HttpServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
    }
    void SetBaseDir(const std::string& path)
    {
        assert(Util::IsDirectory(path) == true);
        _basedir = path;
    }
    void Get(const std::string& pattern, const Handler& handler)
    {
        _get_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void Post(const std::string& pattern, const Handler& handler)
    {
        _post_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void Put(const std::string& pattern, const Handler& handler)
    {
        _put_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void Delete(const std::string& pattern, const Handler& handler) 
    {
        _delete_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void SetThreadCount(int count) { _server.SetThreadCount(count); }
    void Listen() { _server.Start(); }
};